package com.vue.cn.controller;

import com.vue.cn.common.http.AjaxResult;
import com.vue.cn.common.http.StatusEnum;
import com.vue.cn.domin.Admin;
import com.vue.cn.service.AdminService;
import com.vue.cn.utils.code.Code;
import com.vue.cn.utils.sms.SMSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("adminLogin")
public class AdminLoginController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SMSUtil smsUtil;


    @GetMapping("sendCode")
    public AjaxResult getPhoneCode(String phone) {
        //根据手机号查询是否有该管理员
        Admin admin = adminService.findByPhone(phone);
        if (admin == null) {
            return AjaxResult.error(StatusEnum.EEEOR_NOT_REGITER);
        }
        //发送验证码给该用户短信,验证码存入redis缓存,设置5分钟后失效
        redisTemplate.opsForValue().set(phone,Code.numCode(),5L ,TimeUnit.MINUTES);
        smsUtil.sendCode(phone,Code.numCode());

        return AjaxResult.ok();
    }

    @GetMapping("login")
    public AjaxResult adminLogin(HttpSession session, String phone, String code){
        //根据手机号查询是否有该管理员
        Admin byPhone = adminService.findByPhone(phone);
        if (byPhone==null) {
            return AjaxResult.error(StatusEnum.EEEOR_NOT_REGITER);
        }
        //查看缓存中是否有数据，如果没有返回验证码错误
        String s = redisTemplate.opsForValue().get(phone);
        if (StringUtils.isEmpty(code)||!code.equals(s)) {
            return AjaxResult.error(StatusEnum.EEEOR_CODE);
        }
        //将用户信息放入session中，并清除该用户的验证码从缓存中清除
        session.setAttribute("user",byPhone);
        redisTemplate.delete(phone);

        return AjaxResult.ok();
    }
}
